package com.example.handheld4_gsignal_app.ui.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.handheld4_gsignal_app.R;
import com.example.handheld4_gsignal_app.data.Task;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 看板视图任务适配器 - 按状态分组显示任务
 */
public class TaskKanbanAdapter extends BaseAdapter {

    private Context context;
    private List<Object> items; // 包含状态标题和任务对象
    private LayoutInflater inflater;
    private Map<String, List<Task>> tasksByStatus;

    public TaskKanbanAdapter(Context context, List<Task> tasks) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.tasksByStatus = new HashMap<>();
        this.items = new ArrayList<>();
        
        // 按状态分组任务
        groupTasksByStatus(tasks);
        buildItemsList();
    }

    /**
     * 按状态分组任务
     */
    private void groupTasksByStatus(List<Task> tasks) {
        tasksByStatus.clear();
        
        for (Task task : tasks) {
            String status = task.getStatus();
            if (status == null) status = "未知状态";
            
            if (!tasksByStatus.containsKey(status)) {
                tasksByStatus.put(status, new ArrayList<>());
            }
            tasksByStatus.get(status).add(task);
        }
    }

    /**
     * 构建显示项目列表
     */
    private void buildItemsList() {
        items.clear();
        
        // 按预定义顺序添加状态组
        String[] statusOrder = {"待处理", "进行中", "已完成", "已取消"};
        
        for (String status : statusOrder) {
            if (tasksByStatus.containsKey(status) && !tasksByStatus.get(status).isEmpty()) {
                // 添加状态标题
                items.add(new StatusHeader(status, tasksByStatus.get(status).size()));
                
                // 添加该状态下的所有任务
                items.addAll(tasksByStatus.get(status));
            }
        }
        
        // 添加其他状态（如果有的话）
        for (String status : tasksByStatus.keySet()) {
            if (!containsStatus(statusOrder, status) && !tasksByStatus.get(status).isEmpty()) {
                items.add(new StatusHeader(status, tasksByStatus.get(status).size()));
                items.addAll(tasksByStatus.get(status));
            }
        }
    }

    /**
     * 检查状态是否在预定义列表中
     */
    private boolean containsStatus(String[] statusOrder, String status) {
        for (String s : statusOrder) {
            if (s.equals(status)) return true;
        }
        return false;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return 2; // 状态标题和任务项
    }

    @Override
    public int getItemViewType(int position) {
        Object item = items.get(position);
        return item instanceof StatusHeader ? 0 : 1;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Object item = items.get(position);
        
        if (item instanceof StatusHeader) {
            return getStatusHeaderView((StatusHeader) item, convertView, parent);
        } else if (item instanceof Task) {
            return getTaskView((Task) item, convertView, parent);
        }
        
        return convertView;
    }

    /**
     * 获取状态标题视图
     */
    private View getStatusHeaderView(StatusHeader header, View convertView, ViewGroup parent) {
        if (convertView == null || convertView.getTag() == null || !(convertView.getTag() instanceof StatusHeaderViewHolder)) {
            convertView = inflater.inflate(R.layout.task_status_header, parent, false);
            StatusHeaderViewHolder holder = new StatusHeaderViewHolder();
            holder.statusTitle = convertView.findViewById(R.id.status_title);
            holder.taskCount = convertView.findViewById(R.id.task_count);
            convertView.setTag(holder);
        }
        
        StatusHeaderViewHolder holder = (StatusHeaderViewHolder) convertView.getTag();
        holder.statusTitle.setText(header.status);
        holder.taskCount.setText("(" + header.count + "个任务)");
        
        // 设置状态标题颜色
        holder.statusTitle.setTextColor(getStatusColor(header.status));
        
        return convertView;
    }

    /**
     * 获取任务视图
     */
    private View getTaskView(Task task, View convertView, ViewGroup parent) {
        TaskViewHolder holder;
        
        if (convertView == null || convertView.getTag() == null || !(convertView.getTag() instanceof TaskViewHolder)) {
            convertView = inflater.inflate(R.layout.task_list_item, parent, false);
            holder = new TaskViewHolder();
            holder.taskIcon = convertView.findViewById(R.id.task_icon);
            holder.taskTitle = convertView.findViewById(R.id.task_title);
            holder.taskStatus = convertView.findViewById(R.id.task_status);
            holder.taskDescription = convertView.findViewById(R.id.task_description);
            holder.taskCreatedTime = convertView.findViewById(R.id.task_created_time);
            holder.taskAssignee = convertView.findViewById(R.id.task_assignee);
            convertView.setTag(holder);
        } else {
            holder = (TaskViewHolder) convertView.getTag();
        }

        // 设置任务图标
        holder.taskIcon.setText(getTaskIcon(task.getStatus()));
        
        // 设置任务标题
        holder.taskTitle.setText(task.getTitle());
        
        // 设置任务状态
        holder.taskStatus.setText(task.getStatus());
        holder.taskStatus.setTextColor(getStatusColor(task.getStatus()));
        
        // 设置任务描述
        holder.taskDescription.setText(task.getDescription());
        
        // 设置创建时间
        if (task.getCreatedAt() != null) {
            holder.taskCreatedTime.setText(task.getCreatedAt());
        } else {
            holder.taskCreatedTime.setText("未知时间");
        }
        
        // 设置分配人
        holder.taskAssignee.setText("管理员");

        return convertView;
    }

    /**
     * 根据任务状态获取对应的图标
     */
    private String getTaskIcon(String status) {
        if (status == null) return "📋";
        
        switch (status) {
            case "待处理":
                return "⏳";
            case "进行中":
                return "🔄";
            case "已完成":
                return "✅";
            case "已取消":
                return "❌";
            default:
                return "📋";
        }
    }

    /**
     * 根据任务状态获取对应的颜色
     */
    private int getStatusColor(String status) {
        if (status == null) return context.getResources().getColor(R.color.text_primary);
        
        switch (status) {
            case "待处理":
                return context.getResources().getColor(R.color.status_pending);
            case "进行中":
                return context.getResources().getColor(R.color.status_progress);
            case "已完成":
                return context.getResources().getColor(R.color.status_completed);
            case "已取消":
                return context.getResources().getColor(R.color.status_cancelled);
            default:
                return context.getResources().getColor(R.color.text_primary);
        }
    }

    /**
     * 更新任务列表数据
     */
    public void updateTasks(List<Task> newTasks) {
        groupTasksByStatus(newTasks);
        buildItemsList();
        notifyDataSetChanged();
    }

    /**
     * 状态标题数据类
     */
    private static class StatusHeader {
        String status;
        int count;
        
        StatusHeader(String status, int count) {
            this.status = status;
            this.count = count;
        }
    }

    /**
     * 状态标题ViewHolder
     */
    private static class StatusHeaderViewHolder {
        TextView statusTitle;
        TextView taskCount;
    }

    /**
     * 任务ViewHolder
     */
    private static class TaskViewHolder {
        TextView taskIcon;
        TextView taskTitle;
        TextView taskStatus;
        TextView taskDescription;
        TextView taskCreatedTime;
        TextView taskAssignee;
    }
}